package cn.lj.security;

import cn.lj.exception.CaptchaException;
import cn.lj.response.Const;
import cn.lj.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @file: CaptchaFilter
 * @version: 1.0
 * @Description: 验证码过滤器
 * 图片验证码校验过滤器，在登录过滤器前
 * @author: 李津
 * @date: 2021-05-21 16:36
 * 本代码要注意的事项、备注事项等
 */

@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    private final RedisUtil redisUtil;
    private final LoginFailureHandler loginFailureHandler;
    @Autowired
    public CaptchaFilter(RedisUtil redisUtil, LoginFailureHandler loginFailureHandler) {
        this.redisUtil = redisUtil;
        this.loginFailureHandler = loginFailureHandler;
    }

    /**
     * 校验主方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String url = httpServletRequest.getRequestURI();

        if ("/login".equals(url) && httpServletRequest.getMethod().equals("POST")) {
            try{
                // 校验验证码
                validate(httpServletRequest);
            } catch (CaptchaException e) {
                // 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    /**
     * 校验验证码逻辑
     * @param httpServletRequest
     */
    private void validate(HttpServletRequest httpServletRequest) {

        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("randomKey");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
            throw new CaptchaException("验证码错误");
        }

        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))) {
            throw new CaptchaException("验证码错误");
        }

        // 去除验证码，一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY, key);
    }
}
